package cn.edu.zafu.bigdata.x.zhouyuyan.work8;

import java.io.*;
import java.util.Scanner;

public class FileOperations {
    public static void writeToFile(String fileName,String content){
        File file = new File("src/main/java/cn/edu/zafu/bigdata/x/zhouyuyan/work8/file/" + fileName);
        try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(content);
            System.out.println("文件写入成功："+fileName);
        }catch (IOException e){
            System.err.println("写入文件时出错："+e.getMessage());
        }
    }

    public static void readFromFile(String fileName){
        File file = new File("src/main/java/cn/edu/zafu/bigdata/x/zhouyuyan/work8/file/"+fileName);
        try(BufferedReader reader = new BufferedReader(new FileReader(file))){
            String line;
            while ((line = reader.readLine()) != null){
                System.out.println(line);
            }
            System.out.println("文件内容读取完毕。");
        }catch (IOException e){
            System.err.println("读取文件时出错："+e.getMessage());
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入文件名（如2022010101.txt）：");
        String fileName = scanner.nextLine();

        System.out.println("请输入要写入文件的文本内容：");
        StringBuilder contentBuilder = new StringBuilder();
        String line;
        while(!(line = scanner.nextLine()).equals("")){
            contentBuilder.append(line).append(System.lineSeparator());
        }
        String content = contentBuilder.toString();

        writeToFile(fileName,content);
        System.out.println("文件内容：");
        readFromFile(fileName);

        scanner.close();
    }
}
